import { ref } from 'vue';

export default {
	beforeMount(el, binding) {
		// 创建一个 ref 来存储 loading 状态
		const isLoading = ref(false);

		// 将 loading 状态和方法挂载到 el 上，以便在指令中使用
		el._loading = {
			isLoading,
			showLoading() {
				isLoading.value = true;
				// el.style.position = 'relative'; // 确保 loading 层能正确显示
				// const loadingEl = document.createElement('img');
				const loadingEl = document.createElement('img');
				loadingEl.src = 'https://mp-15ab7795-d8b1-4b2f-a41e-493ce57cc1e7.cdn.bspapp.com/images/loading.svg';
				loadingEl.style.position = 'fixed';
				loadingEl.style.top = '50%';
				loadingEl.style.left = '50%';
				loadingEl.style.width = '100rpx';
				loadingEl.style.height = '100rpx';
				loadingEl.style.backgroundColor = 'rgba(255, 255, 255, 0.8)';
				loadingEl.style.transform = 'translate(-50%, -50%)';
				loadingEl.style.zIndex = '9999'; // 确保在所有内容之上显示
				el.appendChild(loadingEl);
			},
			hideLoading() {
				isLoading.value = false;
				const loadingEl = el.querySelector('img');
				if (loadingEl) {
					el.removeChild(loadingEl);
				}
			}
		};

		// 根据传入的值决定是否立即显示 loading
		if (binding.value) {
			el._loading.showLoading();
		}
	},
	updated(el, binding) {
		// 如果值发生变化，根据新值显示或隐藏 loading
		if (binding.value !== binding.oldValue) {
			if (binding.value) {
				el._loading.showLoading();
			} else {
				el._loading.hideLoading();
			}
		}
	},
	unmounted(el) {
		// 组件卸载时，清理 loading 层
		el._loading.hideLoading();
	}
};